<?php
/**
 * Created by PhpStorm.
 * User: houju
 * Date: 2015/9/17
 * Time: 20:46
 */
namespace Home\Controller;

use Think\Controller;



class IndexController extends Controller
{

    public $result = array(
        'flag' => '',
        'content' => ''
    );

    public function downSalaryXls(){
        $xlsName  = "TeacherSalary";
        $xlsCell  = array(
            array('id','老师ID'),
            array('relname','老师姓名'),
            array('salary','老师工资'),
        );
        $xlsModel = M('user_teacher');
        //$where = " relname!='' and salary>=100";
        $where = " relname!=''  and salary!=0";
        $xlsData  = $xlsModel->where($where)->Field('id,relname,salary')->select();
        /*foreach($xlsData as $k=>$v){
            $xlsData[$k]['salary'] = (int)($v['salary']/100)*100;
        }*/
        $this->exportExcel($xlsName,$xlsCell,$xlsData);
    }
    /**
    +----------------------------------------------------------
     * Export Excel | 2013.08.23
     * Author:HongPing <hongping626@qq.com>
    +----------------------------------------------------------
     * @param $expTitle     string File name
    +----------------------------------------------------------
     * @param $expCellName  array  Column name
    +----------------------------------------------------------
     * @param $expTableData array  Table data
    +----------------------------------------------------------
     */
    public function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $_SESSION['loginAccount'].date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        Vendor('PHPExcel.PHPExcel','','.php');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    public function index()
    {
        $where = " user_teacher.star = 1";
        $model = M("user_teacher");
        $data = $model->join('user u ON u.id = user_teacher.user_id')->where($where)->order('u.id desc')->limit(6)->field('user_teacher.*,u.phone')->select();
        $this->assign('data',$data);
        $this->display('index');
    }

    public function register()
    {
        if (IS_POST) {
            if (!A('Pub/Code')->checkCode(I('post.code'))) {
                $this->error('验证码错误');
            };
            $user = M('user');
            $data['phone'] = I('post.phone');
            if ($user->where($data)->find()) {
                $this->error('该手机号已经注册');
            }
            $sms_salt = I('post.sms_salt');
            $home = new DefaultController();
            $content = $home->check_phone_salt($data['phone'], 1, $sms_salt);
            if ($content['flag'] != 1) {
                $this->error($content['content']);
            }
            $data['salt'] = $home->generate_phone_random(6);
            $data['password'] = md5(I('post.password') . $data['salt']);
            $data['type'] = I('post.type');
            if ($data['type'] == 1) {
                $data['status'] = 0;
            }
            $data['addtime'] = date('Y-m-d');
            $result = $user->data($data)->add();
            if ($data['type'] == 1 && $result) {
                for ($i = 1; $i <= 7; $i++) {
                    $user_date['user_id'] = $result;
                    $user_date['week'] = $i;
                    M('user_date')->add($user_date);
                }
            }
            if ($result){
                $data1['user_id'] = $result;
                $data1['avatar']  = "upload/2016-01-01/56867ba7ac3ff.jpg";
                M('user_teacher')->add($data1);                
                session('phone', I('post.phone'));
                session('type', I('post.type'));
                session('id', $result);
                if($data['type'] == 1){
                    $this->success('请填写自己的信息，方便审核', U('Home/Teacher/center'), 2);
                }else{
                    $this->success('注册成功，去首页', U('index'), 1);
                }
                
            }            
        } else {
            $this->display('register');
        }
    }

    public function registerjs()
    {
        if (IS_POST) {
            if (!A('Pub/Code')->checkCode(I('post.code'))) {
                $data['error'] = 1;
                $data['msg'] = '验证码错误';
                echo json_encode($data);die();
            };
            $user = M('user');
            $data['phone'] = I('post.phone');
            if ($user->where($data)->find()) {
                $data['error'] = 1;
                $data['msg'] = '该手机号已经注册';
                echo json_encode($data);die();
            }
            $sms_salt = I('post.sms_salt');
            $home = new DefaultController();
            $content = $home->check_phone_salt($data['phone'], 1, $sms_salt);
            if ($content['flag'] != 1) {
                //$this->error($content['content']);
                $data['error'] = 1;
                $data['msg'] = '手机验证码错误';
                echo json_encode($data);die();
            }
            $data['salt'] = $home->generate_phone_random(6);
            $data['password'] = md5(I('post.password') . $data['salt']);
            $data['type'] = I('post.type');
            if ($data['type'] == 1) {
                $data['status'] = 0;
            }
            $data['addtime'] = date('Y-m-d');
            $result = $user->data($data)->add();
            if ($data['type'] == 1 && $result) {
                for ($i = 1; $i <= 7; $i++) {
                    $user_date['user_id'] = $result;
                    $user_date['week'] = $i;
                    M('user_date')->add($user_date);
                }

            }
            if ($result){
                $data1['user_id'] = $result;
                $data1['avatar']  = "/2016-01-01/56867ba7ac3ff.jpg";
                M('user_teacher')->add($data1);
                session('phone', I('post.phone'));
                session('type', I('post.type'));
                session('id', $result);
                if($data['type'] == 1){
                    $data['error'] = 0;
                    $data['msg'] = '请填写自己的信息，方便审核';
                }else{
                    $data['error'] = 0;
                    $data['msg'] = '注册成功，去首页';
                }
            }
            echo json_encode($data);
        } else {
            $this->display('register');
        }
    }

    public function login()
    {
        (new DefaultController())->session();
        if (IS_POST) {
            if (!A('Pub/Code')->checkCode(I('post.code'))) {
                $this->error('验证码错误');
            };
            $user = M('user');
            $data['phone'] = I('post.phone');
            $user_info = $user->where($data)->find();
            $password = md5(I('post.password') . $user_info['salt']);
            if ($password == $user_info['password']) {
                session('phone', $data['phone']);
                session('type', $user_info['type']);
                session('id', $user_info['id']);
                $this->success('登录成功', U('index'), 1);
            } else {
                $this->error('用户名和密码不匹配');
            }
        } else {
            $this->display('login');
        }
    }

    public function loginjs()
    {
        (new DefaultController())->session();
        if (IS_POST) {
            if (!A('Pub/Code')->checkCode(I('post.code'))) {
                $data['error'] = 1;
                $data['msg'] = '验证码错误';
            };
            $user = M('user');
            $data['phone'] = I('post.phone');
            $user_info = $user->where($data)->find();
            $password = md5(I('post.password') . $user_info['salt']);
            if ($password == $user_info['password']) {
                session('phone', $data['phone']);
                session('type', $user_info['type']);
                session('id', $user_info['id']);
                $data['error'] = 0;
                $data['msg'] = '登陆成功';
            } else {
                $data['error'] = 1;
                $data['msg'] = '用户名和密码不匹配';
            };
            echo json_encode($data);
        } else {
            $this->display('login');
        }
    }

    /*
     * 搜索老师列表
     */
    public function teacherList()
    {
        $where = "  u.status = 1 AND u.type = 1 AND user_teacher.user_id <> '' ";
        $url = '';

        //页码
        if (I('get.page')) {
            $page = I('get.page');
        } else {
            $page = 1;
        }

        //性别搜索
        if (I('get.sex')) {
            $filter['sex'] = (int)I('get.sex');
            $url .= '&sex=' . $filter['sex'];
            $where .= " AND user_teacher.sex =  " . $filter['sex'];
        } else {
            $filter['sex'] = 0;
        }

        //年级搜索
        if (I('get.grade')) {
            $filter['grade'] = (int)I('get.grade');
            $url .= '&grade=' . $filter['grade'];
            $where .= " AND   find_in_set(" . $filter['grade'] . ", user_teacher.grade)";
        } else {
            $filter['grade'] = 0;
        }

        //科目
        if (I('get.lesson')) {
            $filter['lesson'] = (int)I('get.lesson');
            $url .= '&lesson=' . $filter['lesson'];
            $where .= " AND   find_in_set(" . $filter['lesson'] . ", user_teacher.lesson)";
        } else {
            $filter['lesson'] = 0;
        }

        //姓名搜索
        if (I('get.name')) {
            $filter['name'] = (int)I('get.name');
            $url .= '&name=' . $filter['name'];
            $where .= " AND user_teacher.relname  LIKE '%" . $filter['relname'] . "%'";
        } else {
            $filter['name'] = 0;
        }

        //学校
        if (I('get.school')) {
            $filter['school'] = trim(I('get.school'));
            $url .= '&school=' . $filter['school'];
            $where .= " AND user_teacher.school =" . $filter['school'];
        } else {
            $filter['school'] = 0;
        }

        $limit = 8;
        $start = ($page - 1) * $limit;

        $model = M("user_teacher");
        $data = $model->join('user u ON u.id = user_teacher.user_id')->where($where)->order('u.id desc')->limit($start, $limit)->field('user_teacher.*,u.is_certified')->select();
        if($data){
            $default = new DefaultController();
            foreach ( $data as $k => $v){
                if($v['grade']){
                    $data[$k]['grade'] = $default->lesson(explode(",", $v['grade']),'grade');
                }
                if($v['lesson']){
                    $data[$k]['lesson'] = $default->lesson(explode(",", $v['lesson']),'lesson');
                }
                if($v['school']){
                     $data[$k]['school'] = $default->lesson($v['school'],'school');
                }
            }
        }

        $total = $model->join('user u ON u.id = user_teacher.user_id')->where($where)->count();
        $pagination = new \Pub\Controller\PaginationController();
        $pagination->total = $total;
        $pagination->page = $page;
        $pagination->limit = $limit;
        $pagination->url = U('Index/teacherList') . '?page={page}' . $url;
        $render = $pagination->render();

        $new_url = U('Index/teacherList') . '?page={page}' . $url;

        $assign = array();
        $assign['lesson'] = include './Application/Pub/Dictionaries/lesson.php';
        $assign['grade'] = include './Application/Pub/Dictionaries/grade.php';
        $assign['school'] = include './Application/Pub/Dictionaries/school.php';
        $assign['data'] = $data;
        $assign['render'] = $render;
        $assign['url'] = $new_url;
        $assign['filter'] = $filter;

        $this->assign($assign);
        $this->display('teacherlist');
    }


    public function teacherDetail()
    {
        $data = M('user_teacher')->where(array('user_id' => I('get.id')))->find();
        if($data){
            $default = new DefaultController();
            if($data['grade']){
                $data['grade'] = $default->lesson(explode(",", $data['grade']),'grade');
            }
            if($data['lesson']){
                $data['lesson'] = $default->lesson(explode(",", $data['lesson']),'lesson');
            }
            if($data['school']){
                 $data['school'] = $default->lesson($data['school'],'school');
            }
            $data['avatar'] = htmlentities($data['avatar']);
        }
        $date = M('user_date')->where(array('user_id' => I('get.id')))->select();
        $this->assign('data', $data);
        $this->assign('date', $date);
        $this->display('teacherDetail');
    }


    public function department_list()
    {
        if (IS_POST) {
            foreach (I('post.') as $key => $val) {
                $where[$key] = array('like', array('%' . $val . '%'), 'AND');
            }
            $data['department'] = M('user_department')->where($where)->select();
            $data['form'] = I('post.');
            $this->assign($data);
        } else {
            $data['department'] = M('user_department')->select();
            $this->assign($data);
        }
        $this->display('department_list');
    }

    public function departmentDetail()
    {
        $data['detail'] = M('user_department')->where(I('get.'))->find();
        $this->assign($data);
        $this->display('departmentDetail');
    }

    public function logoout()
    {
        session('phone', null);
        session('id', null);
        session('type', null);
        $this->redirect('/Home/Index/index');
    }

    /*
     * 生成短信验证码
     * //$data['type'] 1 注册 2：忘记密码
     */
    public function phoneSalt()
    {
        $result = array('flag' => 0, 'content' => '', 'code' => '');

        if (IS_POST) {
            $data['phone'] = I('post.phone');
            $data['type'] = I('post.type');
            $member_info = M('User')->where(array('phone' => $data['phone']))->select();
            $home = new DefaultController();
            if (!preg_match("/1[3458]{1}\d{9}$/", $data['phone'])) {
                $result['flag'] = 2;
                $result['content'] = '手机号码格式不正确';
            } else if ($data['type'] == 1 && $member_info) {
                $result['flag'] = 3;
                $result['content'] = '手机号码已存在';
            } else if ($data['type'] == 2 && empty ($member_info)) {
                $result['flag'] = 4;
                $result['content'] = '手机号码不存在';
            } else {
                $data['salt'] = $home->generate_phone_random(6);
                $data['happen_time'] = time();
                $data['times'] = 0;
                $data['is_used'] = 0;
                $data['ip'] = $_SERVER['REMOTE_ADDR'];
                $home->sendSMS($data['phone'], $data['salt']);
                M('sms_record')->data($data)->add();
                $result['flag'] = 1;
                $result['content'] = '发送成功';
                $result['code'] = $data['salt'];
            }
        }
        $this->ajaxReturn($result);
    }


    /*
     * 下单
     */
    public function makeOrder()
    {
        $id = session('id');
        $type = session('type');
        $result = $this->result;
        if (IS_POST) {
            if (!$id) {
                $result = array(
                    'flag' => 2,
                    'content' => '您未登录',
                );
            } elseif ($type != 1) {
                $result = array(
                    'flag' => 3,
                    'content' => '您的身份不是老师',
                );
            } else {
                $requirement_id = I('post.requirement_id');
                $model = M('order_form');
                $flag = $model->where(array('user_id' => $id, 'requirement_id' => $requirement_id))->find();
                if ($flag) {
                    $result = array(
                        'flag' => 4,
                        'content' => '您已下过此订单',
                    );
                } else {
                    $date_first = date('Y-m-d');
                    $date_last = date("Y-m-d", strtotime("+1 day"));
                    $where = " user_id = $id  AND date>='" . $date_first . "' AND date< '" . $date_last . "'";
                    $total = $model->where($where)->count();
                    if ($total > 5) {
                        $result = array(
                            'flag' => 5,
                            'content' => '当天下单量最多5次',
                        );
                    } else {
                        $order = array(
                            'order_sn' => (new DefaultController())->orderSn(),
                            'user_id' => $id,
                            'requirement_id' => $requirement_id,
                            'date' => date('Y-m-d H:i:s')
                        );
                        $model->data($order)->add();
                        $result = array(
                            'flag' => 1,
                            'content' => '下单成功',
                        );
                    }
                }
            }
        }
        $this->ajaxReturn($result);
    }
    
    
    /*
     * 家长预约
     */
    public function parentOrder(){
        $id = session('id');
        $type = session('type');
        $result = $this->result;
        if(IS_POST){
            if (!$id) {
                $result = array(
                    'flag' => 2,
                    'content' => '您未登录',
                );
            } elseif ($type != 2) {
                $result = array(
                    'flag' => 3,
                    'content' => '您的身份不是家长',
                );
            } else {
                $model = M('order_form');
                if(I('post.teacher_id')){
                    $id = I('post.teacher_id');
                    $date_first = date('Y-m-d');
                    $date_last = date("Y-m-d", strtotime("+1 day"));
                    $where = " user_id = $id   AND date>='" . $date_first . "' AND date< '" . $date_last . "'";
                    $total = $model->where($where)->count();
                    if($total>5){
                        $result = array(
                            'flag' => 5,
                            'content' => '当天下单量最多5次',
                        );
                    }else{
                        $default = new DefaultController();

                        $data = I('post.');              
                        $data['order_sn'] = $default->orderSn();
                        $data['date'] = I('post.time');
                        $data['user_id'] = session('id');
                        $form = M('requirement');
                        /*$total = $form->where(array('teacher_id' => $data['teacher_id']))->count();
                        if($total){
                            $result = array(
                                'flag' => 2,
                                'content' => '您已预约该老师',
                            );
                            $this->ajaxReturn($result);
                        }*/
                        
                        $requirement_id = $form->add($data);

                        $order['order_sn'] = $data['order_sn'];
                        $order['teacher_id'] = I('post.teacher_id');
                        $order['user_id'] = session('id');
                        $order['coursenum'] = 0;
                        $order['requirement_id'] = $requirement_id;
                        $order['date'] = I('post.time');
                        
                        $model->add($order);
                        $result = array(
                            'flag' => 1,
                            'content' => '订单已提交，请等待工作人员处理。其间我们的工作人员可能会电话联系您，请保持电话畅通。',
                        );
                    }
                }                 
            }
        }
        $this->ajaxReturn($result);
    }


   /*
    * 家长需求预约
    */
    public function fastparentOrder(){
        $model = M('order_form');
        $form = M('requirement');
        $result = array(
            'flag' => '',
            'content' => ''
        );
        if(IS_POST){
            $default = new DefaultController();
            $data = I('post.');
            $data['order_sn'] = $default->orderSn();
            $data['date'] = I('post.time');
            $data['user_id'] = 0;
            $requirement_id = $form->add($data);
            if($requirement_id){
                $result = array(
                    'flag' => 1,
                    'content' => '您的需求已发布，我们的工作人员会尽快与您联系。',
                );
            }
        }
        $this->ajaxReturn($result);
    }
    /*
     * 忘记密码密码
     */

    public function forgetPassword()
    {
        $result = $this->result;
        if (IS_POST) {
            $sms_code = I('post.sms_salt');
            $phone = I('post.phone');
            $password = I('post.password');
            $confirm_password = I('post.confirm_password');
            $home = new DefaultController();
            $content = $home->check_phone_salt($phone, 2, $sms_code);

            if ($content['flag'] != 1) {
                $this->error($content['content']);
            }
            if ($password != $confirm_password) {
                $content['content'] =  '密码输入不一致';
                $this->error($content['content']);
            } else {
                $data['salt'] = $home->generate_phone_random(6);
                $data['password'] = md5($password . $data['salt']);
                M('user')->where(array('phone' => $phone))->save($data);
                $this->success('修改成功，请重新登录', U('Index/login'), 1);
                exit;
            }
        }
        $this->assign($data);
        $this->display('forgetPassword');

    }
    
    /*
     * 添加推荐
     */
    public function addTeacher(){
        $result = $this->result;
        if(IS_POST){
           $model =  M('recommendation');
           $user =  M('user');
           $where = " phone =  ".I('post.phone');
           $result1 = $user->where($where)->find();
           $result2 = $model->where($where)->find();
           if($result1 || $result2){
               $this->ajaxReturn($result = array('flag' => '1',
                 'content' => '用户已存在'));
           }
           $data = array(
               'user_id' => I('post.user_id'),
               'adddate' => date('Y-m-d H:i:s'),
               'phone' => I('post.phone'),
               'remarks' => I('post.remarks'),
           );
           $id = $model->add($data);
           if($id){
               $result = array(
                 'flag' => '1',
                 'content' => '推荐成功',
               );
           }else{
               $result = array(
                 'flag' => '1',
                 'content' => '推荐失败',
               );
           }
        }
        $this->ajaxReturn($result);
    }


}